package com.abc.xxx.controller;

import com.abc.xxx.model.Dept;
import com.abc.xxx.model.User;
import com.abc.xxx.util.Result;
import com.alibaba.fastjson.JSON;
import com.baomidou.mybatisplus.core.conditions.query.QueryWrapper;
import com.abc.xxx.service.DeptService;
import lombok.extern.slf4j.Slf4j;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.security.core.annotation.AuthenticationPrincipal;
import org.springframework.web.bind.annotation.*;

import java.time.LocalDateTime;
import java.util.List;

import static org.apache.commons.lang3.StringUtils.isBlank;
import static org.apache.commons.lang3.StringUtils.isNotBlank;

@Slf4j
@RestController
@RequestMapping("/depts")
public class DeptController {

    private static final String NO_AUTH = "权限不足：只有超级管理员或企业主账号才能";

    @Autowired

    private DeptService deptService;

    @GetMapping
    public Result findDepts(@AuthenticationPrincipal User user,
                            @RequestParam(value = "key", required = false) String key) {
        String oper = "查询部门";
        log.info("====>{}, key: {}", oper, key);
        QueryWrapper<Dept> w = new QueryWrapper<>();
        if (isNotBlank(key)){
            w.like("`name`", key);
        }
        List<Dept> list = deptService.list(w);
        return Result.success(oper).list(list);
    }

    @PostMapping
    public Result createDept(@AuthenticationPrincipal User user,
                             @RequestBody String body,
                             @RequestParam("createRootDept") Boolean createRootDept) {
        String oper = "新增";
        log.info("====>{}, body: {}", oper, body);

        Dept form = JSON.parseObject(body, Dept.class);
        if (isBlank(form.getName())) {
            return Result.error(oper).msg("部门名称不能为空");
        }

        if (createRootDept) {
            form.setParent(0);
            form.setParents("0,");
        }

        if (form.getParent() == null || isBlank(form.getParents())) {
            return Result.error(oper).msg("找不到父级部门，无法新增部门");
        }

        deptService.save(form);

        return Result.success(oper).data("id", form.getId());
    }

    @PatchMapping("/{deptId}")
    public Result updateDept(@AuthenticationPrincipal User user,
                             @PathVariable("deptId") Integer deptId,
                             @RequestBody String body) {
        String oper = "更新部门";
        log.info("====>{}, deptId: {}, body: {}", oper, deptId, body);

        // 共同数据校验
        Dept form = JSON.parseObject(body, Dept.class);
        String err = null;
        if (form.getId() == null) err = "部门id不能为空";
        if (isBlank(form.getName())) err = "部门名称不能更新为空";
        if (isNotBlank(err)) return Result.error(oper).msg(err);

        // 更新的字段
        Dept dept = new Dept();
        dept.setId(form.getId());
        dept.setName(form.getName());

        // 执行更新
        deptService.updateById(dept);
        return Result.success(oper).data("time", LocalDateTime.now());
    }

    @DeleteMapping("/{deptId}")
    public Result deleteDept(@AuthenticationPrincipal User user,
                                 @PathVariable("deptId") Integer deptId) {
        String oper = "删除部门";
        log.info("====>{}, deptId: {}", oper, deptId);

        // 数据校验
        if (deptId == null) {
            return Result.error(oper).msg("无法删除：部门id不能为空");
        }
        if (deptService.hasChildrenDepts(deptId)){
            return Result.error(oper).msg("无法删除：该部门有下级部门");
        }

        // 执行删除
        deptService.removeById(deptId);
        return Result.success(oper);
    }


}
